package com.CST.service.impl.zx;

import com.CST.dto.zx.ProSelDTO;
import com.CST.dto.zx.ProjectDTO;
import com.CST.entity.cb.BdDepartment;
import com.CST.entity.cb.BdSysUser;
import com.CST.entity.zx.ZX_Audit;
import com.CST.entity.zx.ZX_Project;
import com.CST.entity.zx.ZxAuth;
import com.CST.entity.zx.ZxViewPerson;
import com.CST.mapper.cst.cb.BdSysUserMapper;
import com.CST.mapper.cst.cb.ZxAuthMapper;
import com.CST.mapper.cst.zx.ZX_AllocationMapper;
import com.CST.mapper.cst.zx.ZX_AuditMapper;
import com.CST.mapper.cst.zx.ZX_FinancialMapper;
import com.CST.mapper.cst.zx.ZX_ProjectInfoMapper;
import com.CST.mapper.dataplatform.BdDepartmentMapper;
import com.CST.service.cb.IBdSysUserService;
import com.CST.service.zx.IZX_AllocationService;
import com.CST.service.zx.IZX_ProjectInfoService;
import com.CST.service.zx.IZX_ViewPersonService;
import com.CST.util.ExcelTransfer;
import com.CST.vo.cb.BdSysUserDeptCodeVO;
import com.CST.vo.zx.AllocationVo;
import com.CST.vo.zx.EntryVo;
import com.CST.vo.zx.ProjectVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class ZX_ProjectInfoServiceImpl extends ServiceImpl<ZX_ProjectInfoMapper, ZX_Project> implements IZX_ProjectInfoService {


    @Autowired
    ZX_FinancialMapper zxFinancialMapper;

    @Autowired
    ZX_ProjectInfoMapper zx_projectInfoMapper;

    @Autowired
    ZX_AuditMapper zxAuditMapper;

    @Autowired
    BdDepartmentMapper departmentMapper;
    @Autowired
    ZX_FinancialMapper financialMapper;
    @Autowired
    BdSysUserMapper bdSysUserMapper;
    @Autowired
    IBdSysUserService userService;

    @Autowired
    IZX_AllocationService allocationService;
    @Autowired
    ZX_AllocationMapper allocationMapper;

    @Autowired
    ZxAuthMapper zxAuthMapper;

    @Autowired
    IZX_ViewPersonService viewPersonService;

    @Override
    public List<BdSysUserDeptCodeVO> getDeptByRootCode(String rootDept) {
        List<BdDepartment> deptByRootCode = zx_projectInfoMapper.getDeptByRootCode(rootDept);
        List<BdSysUserDeptCodeVO> list = new ArrayList<>();
        deptByRootCode.forEach(t -> {
            BdSysUserDeptCodeVO deptCodeVO = new BdSysUserDeptCodeVO();
            deptCodeVO.setDeptCode(t.getDeptCode());
            deptCodeVO.setDeptName(t.getDeptName());
            list.add(deptCodeVO);
        });
        return list;
    }

    @Override
    public ZX_Project getFinancialByCode(String financial_code) {
        return zx_projectInfoMapper.getFinancialByCode(financial_code);
    }

    @Override
    public void addProject(ZX_Project t) {
        zx_projectInfoMapper.addProject(t);
    }

    @Override
    public Integer deleteProject(String financialCode) {
        return zx_projectInfoMapper.deleteProject(financialCode);
    }

    /**
     * @描述 1.项目编码的判重
     * -  新项目 ，老项目没有填编号 ，填了编号
     * @创建人 ellen
     * @创建时间 2023-03-17 12:53
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProjectInfo(ProjectDTO projectDTO) {
        ZX_Project projectInfo = new ZX_Project();
        BeanUtils.copyProperties(projectDTO, projectInfo);
        projectInfo.setUpdateTime(LocalDateTime.now());
        zx_projectInfoMapper.updateProjectInfo(projectInfo);
        if (projectDTO.getAllocations() != null && projectDTO.getAllocations().size() > 0) {
            //先删除
            allocationMapper.deleteByFinancialCode(projectInfo.getFinancialCode());
            //后插入
            allocationMapper.insertBatchZxAllocation(projectDTO.getAllocations());
        }
    }

    @Override
    public void downloadFile(ProSelDTO proSelDTO, HttpServletResponse response) {
        ExcelTransfer<ProjectVo> excelTransfer = new ExcelTransfer<>();
        List<ProjectVo> projectVoList = this.getProjectVos(proSelDTO);
        try {
            excelTransfer.exportExcel(response, projectVoList, "项目信息", "项目信息详情", ProjectVo.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<BdSysUser> getLeader(String userName) {
        return bdSysUserMapper.getAllUsers(userName);
    }

    @Override
    public void importProject(MultipartFile file) {
        ExcelTransfer<ZX_Project> excelTransfer = new ExcelTransfer<>();
        excelTransfer.importExcel(file, this, ZX_Project.class);
    }

    @Override
    public Integer isExistsRelationByFinancialCode(String financialCode) {
        return zx_projectInfoMapper.isExistsRelationByFinancialCode(financialCode);
    }


    /**
     * @描述 这边拿到用友的数据，封装成一个VO ，插入到自己的项目信息表中
     * @创建人 ellen
     * @创建时间 2023-03-03 10:38
     */
    @Override
    public List<ProjectVo> getProjectVos(ProSelDTO proSelDTO) {
        List<ProjectVo> projectVoList = zx_projectInfoMapper.getProjectVos(proSelDTO);
        return projectVoList;
    }

    @Override
    public ProjectVo getProjectDetail(String financialCode) {
        ProjectVo projectVo = zx_projectInfoMapper.getProjectDetail(financialCode);
        if (projectVo != null) {
            List<AllocationVo> allocationVoList = allocationService.getAllocationList(financialCode);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = null;
            try {
                parse = sdf.parse("2019-01-01");
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            if (allocationVoList == null || allocationVoList.size()==0) {
                AllocationVo info = new AllocationVo();
                info.setFinancialCode(financialCode);
                info.setFinancialName(projectVo.getFinancialName());
                info.setCreateTime(parse);
                info.setAppropriationBalance(BigDecimal.ZERO);
                allocationVoList.add(info);
                projectVo.setAllocations(new ArrayList<>());

            }
            projectVo.setAllocations(allocationVoList);
            List<ZxViewPerson> zxViewPersonList = viewPersonService.getZxViewPersonList(financialCode);
            if(CollectionUtils.isNotEmpty(zxViewPersonList))
            {
                projectVo.setViewPersons(zxViewPersonList);

                //这里作特殊处理,选中人的数据源
                List<String> userNameList = zxViewPersonList.stream().map(t->t.getUserName()).collect(Collectors.toList());
                List<BdSysUser> bdSysUserList = bdSysUserMapper.getSelectUser(userNameList);
                projectVo.setViewPersonsSource(bdSysUserList);
            }

        }
        return projectVo;
    }


    @Override
    public List<ZX_Project> getCurrentProInfo() {
        return zx_projectInfoMapper.getCurrentProInfo();
    }

    @Override
    public List<EntryVo> getProjectType(String type, HttpServletRequest request) {
        String userId =request.getHeader("userName");
        //修改专项管理-项目档案，根据登录人对应的项目类别关系，关联出来下拉列表有多少个
        return zx_projectInfoMapper.getProjectType(type,userId);
    }

    @Override
    public List<BdDepartment> getRootDept() {
        return zx_projectInfoMapper.getRootDept();
    }

    @Override
    public void deleteProjectByUser(String userId, String financialCode) {
        //根据userId判断是否是审批权限组里
        LambdaQueryWrapper<ZxAuth> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZxAuth::getUserid, userId);
        ZxAuth userInfo = zxAuthMapper.selectOne(queryWrapper);
        if (userInfo != null) {
            //直接删除原始数据(包括ZX_ETL_FINANCIAL_INFO,ZX_PROJECT)
            zxFinancialMapper.deleteFinancialProject(financialCode);
            zx_projectInfoMapper.deleteProject(financialCode);
        } else {
            BdSysUser user = bdSysUserMapper.getUserById(userId);
            //生成审批数据(ZX_Audit),待审批通过后再删除原始数据
            ZX_Audit info = new ZX_Audit();
            ProjectVo projectDetail = zx_projectInfoMapper.getProjectDetail(financialCode);
            if (projectDetail != null) {
                info.setFinancialCode(projectDetail.getFinancialCode());
                info.setFinancialName(projectDetail.getFinancialName());
                if (user != null) {
                    info.setApplyPersonAccount(user.getUserName());
                    info.setApplyPerson(user.getRealName());
                } else {
                    info.setApplyPersonAccount("");
                    info.setApplyPerson("");
                }
                info.setApplyDeptCode(projectDetail.getDeptCode());
                info.setApplyDeptName(projectDetail.getDeptName());
                info.setApplyTime(LocalDateTime.now());
                info.setStatus(0);
                info.setComments("");
                info.setProjectCode(projectDetail.getProjectCode());
                info.setEntryId(projectDetail.getEntryId());
                info.setEntryName(projectDetail.getEntryName());
                info.setProjectInfo(projectDetail.getProjectInfo());
                info.setUserId(projectDetail.getUserId());
                info.setUserName(projectDetail.getUserName());
                zxAuditMapper.addAudit(info);
            }

        }
    }

}
